<?php
namespace ThirdPay;

use ThirdPay\KeyFormat;
use ThirdPay\KeyWorker;
use ThirdPay\Tools;
/**
*  阅凯支付
**/

class YueKaiPay
{
	const ORDER_URL = '/paygateway/mbpay/order/v1';
	

	public $merNo;		//商户编号
	public $merAccount;//商户标识
	public $privateKey;//秘钥
	public $publicKey; //公钥
	public $domain;
	public $debug = false;


	public function __construct($merNo,$merAccount,$privateKey,$publicKey)
	{
		$this->merNo = $merNo;
		$this->merAccount = $merAccount;
		$this->privateKey = $privateKey;
		$this->publicKey = $publicKey;
		if($this->debug){
			$this->domain = "http://paytest.mihuajinfu.com";
		}else{
			$this->domain = "https://platform.mhxxkj.com";
		}
	}

	public function order($param) {
		$data = array(
			'merAccount' => $this->merAccount,//商户标识
			'merNo' => $this->merNo,//商户编号
			'time' => time(),//时间戳
			'orderId' => $param['order'],//订单号
			'amount' => $param['money'],//交易金额(分)
			'product' => '购买阅读币',//商品
			'productDesc' => $param['productDesc'],//商品描述
			'payWay' => $param['payWay'],//'WEIXIN'
			'payType' => $param['payType'],//'JSAPI_WEIXIN',
			'openId' =>$param['openId'],//'ojmRm1jJzNSBK-6RxFFdNE30E4_4',
			'userIp' => Tools::get_client_ip(),
			'returnUrl' => $param['returnUrl'],//前端页面回调地址
			'notifyUrl' => $param['notifyUrl'],//后台回调地址
		);
		
		$data['sign'] = $this->getSign($data,$this->privateKey);
		$encode_data = Tools::encryptData($data,$this->privateKey);

		$post_data = array(
			'merAccount' => $this->merAccount,//商户标识
			'data' => $encode_data
		);
		
		$ret = $this->http($this->domain.self::ORDER_URL,$post_data);
		
		$retjson = json_decode($ret,true);
		
		if($retjson["code"] =="000000"){
			if($this->checkSign($retjson["data"],$this->publicKey)){
				return $retjson;	  
			} else {
				return json_encode(array("code"=>"100004","msg"=>"CPS签名验证错误！"));
			}
		}else{
			return $retjson;
		}
	}

	public function http($url,$post_data) {
		$ch = curl_init($url);
		$timeout = 6000;
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_HEADER,0 );
		curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
		$ret = curl_exec($ch);
		curl_close($ch);
		return $ret;
	}


	//签名方式
	public function getSign($params,$signKey)
	{
		ksort($params);
		$data = "";
		foreach ($params as $key => $value) {
		$data .= $value;
		}
		$sign = strtoupper(md5($data.$signKey));
		return $sign;
	}

	//验签
	public function checkSign($params,$signKey) 
	{
		ksort($params);
		$psign = "";
		$data = "";
		foreach ($params as $key => $value) {
		if($key == "sign") {
			$psign = $value;
		} else {
			$data .= $value;
		}
		}
		$sign = strtoupper(md5($data.$signKey));
		if($psign == $sign) {
		  return true;
		} else {
		  return false;
		};
	}
	

}